//
//  womenTableViewController.m
//  A1.0
//
//  Created by lanou3g on 15-3-26.
//  Copyright (c) 2015年 ccandxx. All rights reserved.
//

#import "womenTableViewController.h"
#import "SDRefresh.h"
#import "womenTableViewCell.h"
#import "womenModel.h"
#import "CommonAPI.h"


#import "UIImageView+WebCache.h"
#import "UIImageView+HighlightedWebCache.h"
#import "SDWebImageManager.h"
#import "SDWebImageDecoder.h"

#import "popupView.h"
#import "UIViewController+LewPopupViewController.h"
#import "LewPopupViewAnimationFade.h"
#import "LewPopupViewAnimationSlide.h"
#import "LewPopupViewAnimationSpring.h"
#import "LewPopupViewAnimationDrop.h"

#import "MzTableViewController.h"
#import "ConectViewController.h"
#import "AppDelegate.h"

#import "Reachability.h"

#import "MJRefresh.h"

#import "DownloadViewController.h"
#import "PicDetailModel.h"
@interface womenTableViewController ()
@property (nonatomic, weak) SDRefreshFooterView *refreshFooter;
@property (nonatomic, assign) NSInteger totalRowCount;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *leftButton;
@property (nonatomic,strong)UILabel *warmLabel;



//用于检测网络
@property (nonatomic ,strong)Reachability *r;


@end

@implementation womenTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        
        
    }
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:252/255.0 green:246/255.0 blue:254/255.0 alpha:1.0];
    //隐藏cell之间的分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.tabBarController.tabBar.translucent = NO;


    self.r = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    
    if  ([self.r currentReachabilityStatus]== NotReachable){
        
        UIAlertView *warming = [[UIAlertView alloc]initWithTitle:@"警告" message:@"没有检测到网络,请联网后刷新再试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [warming show];
     
    }
    
    
      [self setupRefresh];
    
    //如果没有刷新到数据,请用户重试
    self.warmLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, [UIScreen mainScreen].bounds.size.height/4, [UIScreen mainScreen].bounds.size.width, 40)];
    
    self.warmLabel.text = @"加载数据中,请稍后或下拉刷新重试";
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    //    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    // dateKey用于存储刷新时间，可以保证不同界面拥有不同的刷新时间
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing) dateKey:@"table"];
    
//#warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"数据正在加载中,请稍后";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.tableView.footerRefreshingText = @"数据正在加载中,请稍后";
}
- (void)headerRereshing
{
    [self.view addSubview:self.warmLabel];
    if (_dataArray.count == 0) {
        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(50, 50, 80, 80)];
        
        indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        
        indicator.backgroundColor = [UIColor clearColor];
        
        indicator.alpha = 0.5;
        indicator.tag = 105;
        
        indicator.layer.cornerRadius = 6;
        indicator.layer.masksToBounds = YES;
        
        [indicator setCenter:CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0)];
        
        [indicator startAnimating];
        [self.view addSubview:indicator];
        [indicator startAnimating];
    }
    // 1.添加数据
    __weak typeof (self) weakSelf = self;
    [CommonAPI firstGirlListData:^(id data) {
        weakSelf.dataArray = data;
        // 刷新表格
        [weakSelf.tableView reloadData];
        [self.warmLabel removeFromSuperview];
        UIActivityIndicatorView  *indicator = (UIActivityIndicatorView *)[self.view viewWithTag:105];
        [indicator stopAnimating];
    }];

    
    // 2.模拟2秒后刷新表格UI（真实开发中，可以移除这段gcd代码）
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView headerEndRefreshing];
            
        
            
  });
}

- (void)footerRereshing
{
    // 1.添加数据
    womenModel *m = self.dataArray.lastObject;
    __weak typeof (self) weakSelf = self;
    [CommonAPI downGirlListstring:m.cTime Data:^(id data) {
        NSArray *arr = [[NSArray alloc]initWithArray:data];
        [weakSelf.dataArray addObjectsFromArray:arr];
        
    }];

    
    // 2.模拟2秒后刷新表格UI（真实开发中，可以移除这段gcd代码）
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView footerEndRefreshing];
    });
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    womenTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"womencell" forIndexPath:indexPath];
    
    womenModel *m = self.dataArray[indexPath.row];
    cell.womenlabel.text = m.title;
    
    NSURL *picurl = [NSURL URLWithString:m.pic];
    //cell选中的颜色为透明
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    [cell.womenimage sd_setImageWithURL:picurl placeholderImage:[UIImage imageNamed:@"cat.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        cell.womenimage.image = image;
    }];
    
    cell.wModel = m;
    return cell;
}


//返回cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //womenModel *m = [[womenModel alloc]init];
    womenModel *m = self.dataArray[indexPath.row];
    
    return [womenTableViewCell cellFloatWithModel:m];
    
}
- (IBAction)sss:(id)sender {
    popupView *view = [popupView defaultPopupView];
    view.parentVC = self;
    [view.button addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
    
    [view.clearButton addTarget:self action:@selector(clearAction) forControlEvents:UIControlEventTouchUpInside];
    
    [view.fiveButton addTarget:self action:@selector(fiveAction) forControlEvents:UIControlEventTouchUpInside];
    
    [view.mzButton addTarget:self action:@selector(mzAction) forControlEvents:UIControlEventTouchUpInside];
    [self lew_presentPopupView:view animation:[LewPopupViewAnimationDrop new] dismissed:^{
        NSLog(@"动画结束");
       
    }];
}


- (void)push
{
    

    NSLog(@"我的收藏");
}

- (void)clearAction
{
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [appDelegate.myCache clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
    
    NSLog(@"清空缓存");
    
    UIAlertView *aleraView = [[UIAlertView alloc]initWithTitle:@"恭喜" message:@"缓存已经清空" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [aleraView show];
}

- (void)fiveAction
{
    NSLog(@"联系我们");
    ConectViewController *coView = [[ConectViewController alloc]init];
    [self.navigationController pushViewController:coView animated:YES];
    
}

- (void)mzAction
{
    MzTableViewController *mzView = [[MzTableViewController alloc]init];
    
    [self.navigationController pushViewController:mzView animated:YES];
    
    NSLog(@"免责声明");
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //womenModel *m = [[womenModel alloc]init];
     womenModel *m  = self.dataArray[indexPath.row];
    PicDetailModel *pm = [[PicDetailModel alloc]init];
    
    pm.pic_h = m.pic_h;
    pm.pic_w = m.pic_w;
    pm.pic = m.pic;
   
    DownloadViewController *dvc = [[DownloadViewController alloc]init];
    dvc.picDM = pm;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self presentViewController:dvc animated:YES completion:nil];
        
    });}

@end
